const express = require('express');
const router = express.Router();
const UserModel = require('../../model/UserModel');
const multer = require('multer');
const upload = multer({ dest: 'public/images/avatar/' });
const fs = require('fs');

/**
 * 伪登录接口 - 只需要用户名，不需要密码
 * 用于前台用户匹配和展示
 */
router.post('/pseudo-login', async (req, res) => {
    try {
        const { username } = req.body;

        if (!username || username.trim() === '') {
            return res.status(400).send({
                code: 400,
                message: '请输入用户名'
            });
        }

        // 查找用户（支持用户名、昵称或ID查找）
        const user = await UserModel.findOne({
            $or: [
                { username: username.trim() },
                { nickname: username.trim() },
                { _id: username.trim() }
            ]
        }).lean();

        if (!user) {
            return res.status(404).send({
                code: 404,
                message: '用户不存在，请检查用户名是否正确'
            });
        }

        // 移除敏感信息
        delete user.password;

        // 处理头像路径
        if (user.avatar) {
            user.avatar = process.env.SERVER_BASE_URL + user.avatar;
        }

        // 返回用户信息（供前端展示和存储）
        res.send({
            code: 200,
            message: '匹配成功',
            data: {
                id: user._id,
                username: user.username,
                nickname: user.nickname || user.username,
                avatar: user.avatar,
                introduction: user.introduction,
                github: user.github,
                gitee: user.gitee,
                csdn: user.csdn
            }
        });
    } catch (error) {
        console.error('伪登录错误:', error);
        res.status(500).send({
            code: 500,
            message: '服务器内部错误'
        });
    }
});

/**
 * 获取用户信息接口 - 通过用户名获取用户公开信息
 */
router.get('/user-info/:username', async (req, res) => {
    try {
        const { username } = req.params;

        const user = await UserModel.findOne({
            $or: [
                { username: username },
                { nickname: username },
                { _id: username }
            ]
        }).lean();

        if (!user) {
            return res.status(404).send({
                code: 404,
                message: '用户不存在'
            });
        }

        // 移除敏感信息
        delete user.password;

        // 处理头像路径
        if (user.avatar) {
            user.avatar = process.env.SERVER_BASE_URL + user.avatar;
        }

        res.send({
            code: 200,
            data: {
                id: user._id,
                username: user.username,
                nickname: user.nickname || user.username,
                avatar: user.avatar,
                introduction: user.introduction,
                github: user.github,
                gitee: user.gitee,
                csdn: user.csdn,
                email: user.email,
                birthday: user.birthday
            }
        });
    } catch (error) {
        console.error('获取用户信息错误:', error);
        res.status(500).send({
            code: 500,
            message: '服务器内部错误'
        });
    }
});

/**
 * 获取所有用户列表（公开信息） - 用于前端选择用户
 */
router.get('/users', async (req, res) => {
    try {
        const users = await UserModel.find()
            .select('_id username nickname avatar introduction')
            .lean();

        // 处理头像路径
        const usersWithFullPath = users.map(user => {
            if (user.avatar) {
                user.avatar = process.env.SERVER_BASE_URL + user.avatar;
            }
            return {
                id: user._id,
                username: user.username,
                nickname: user.nickname || user.username,
                avatar: user.avatar,
                introduction: user.introduction
            };
        });

        res.send({
            code: 200,
            data: usersWithFullPath
        });
    } catch (error) {
        console.error('获取用户列表错误:', error);
        res.status(500).send({
            code: 500,
            message: '服务器内部错误'
        });
    }
});

/**
 * 用户注册接口
 */
router.post('/register', upload.single('avatar'), async (req, res) => {
    try {
        const {
            username,
            password,
            nickname,
            gender,
            phone,
            email,
            introduction,
            github,
            gitee,
            csdn
        } = req.body;

        // 验证必填字段
        if (!username || !password) {
            return res.status(400).send({
                code: 400,
                message: '用户名和密码不能为空'
            });
        }

        if (username.trim() === '' || password.trim() === '') {
            return res.status(400).send({
                code: 400,
                message: '用户名和密码不能为空'
            });
        }

        // 验证头像是否上传
        if (!req.file) {
            return res.status(400).send({
                code: 400,
                message: '请上传头像'
            });
        }

        // 检查用户名是否已存在
        const existingUser = await UserModel.findOne({
            username: username.trim()
        });

        if (existingUser) {
            return res.status(400).send({
                code: 400,
                message: '用户名已存在，请更换'
            });
        }

        // 处理头像文件
        let avatarPath = '';
        if (req.file) {
            // 重命名文件，添加扩展名
            const oldPath = req.file.path;
            const ext = req.file.mimetype.split('/')[1];
            const newPath = `${oldPath}.${ext}`;
            
            fs.renameSync(oldPath, newPath);
            
            // 保存相对路径
            avatarPath = newPath.replace('public', '');
        }

        // 生成用户ID（使用时间戳 + 随机数）
        const userId = Date.now().toString() + Math.floor(Math.random() * 10000);

        // 创建新用户
        const newUser = new UserModel({
            _id: userId,
            username: username.trim(),
            password: password, // 注意：实际项目中应该对密码进行加密
            nickname: nickname?.trim() || username.trim(),
            gender: parseInt(gender) || 0,
            phone: phone?.trim() || '',
            email: email?.trim() || '',
            introduction: introduction?.trim() || '',
            github: github?.trim() || '',
            gitee: gitee?.trim() || '',
            csdn: csdn?.trim() || '',
            avatar: avatarPath,
            name: '',
            girlFriends: '',
            birthday: ''
        });

        await newUser.save();

        // 返回成功信息（不返回密码）
        res.send({
            code: 200,
            message: '注册成功',
            data: {
                id: newUser._id,
                username: newUser.username,
                nickname: newUser.nickname
            }
        });
    } catch (error) {
        console.error('用户注册错误:', error);
        res.status(500).send({
            code: 500,
            message: '服务器内部错误'
        });
    }
});

module.exports = router;

